//
//  PictureBroswerCell.swift
//  测试-图片查看器
//
//  Created by shmily on 15/8/9.
//  Copyright © 2015年 shmilyAshen. All rights reserved.
//

import UIKit

class PictureBroswerCell: UICollectionViewCell {
    
    /// 数据源
    var imageUrl: NSURL?{
        didSet{
            resetScrollView()
            imgView.image = nil
            indicator.startAnimating() // 开始菊花
            
            // 下载图片
            imgView.sd_setImageWithURL(imageUrl) { (img, error, _, _) -> Void in
                if img == nil {
                    print("下载图片失败")
                    return
                }
                self.indicator.stopAnimating() // 停止菊花
                self.imgView.image = img
                self.fitSize()
            }
        }
    }
    
    /// 重设 ScrollView 的偏移属性
    private func resetScrollView() {
        imgView.transform = CGAffineTransformIdentity // 防止只能缩放一次
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    
    private func fitSize() {
        let retio = imgView.image!.size.height / imgView.image!.size.width
        let height = contentView.bounds.width * retio // 图像缩放后的高度
        let s = CGSize(width: contentView.bounds.width, height: height)
            
        if height > contentView.bounds.height { // 顶部显示
            imgView.frame = CGRect(origin: CGPointZero, size: s)
            scrollView.contentSize = s
        } else { // 居中显示
            let y = (contentView.bounds.height - height) * 0.5
            imgView.frame = CGRect(origin: CGPointZero, size: s)
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
        }
    }
    
    //MARK:- 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 布局视图
    private func setupUI() {
        contentView.addSubview(scrollView)
        scrollView.frame = CGRect(x: 0, y: 0, width: contentView.bounds.width - 20, height: contentView.bounds.height)
        
        scrollView.delegate = self
        scrollView.maximumZoomScale = 2.0
        scrollView.minimumZoomScale = 0.5
        scrollView.backgroundColor = UIColor.darkTextColor() //TODO:- 颜色需要删掉
        scrollView.addSubview(imgView)
        
        // 菊花布局
        contentView.addSubview(indicator)
        indicator.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
    }
    
    // scrollView collectionView 内部
    private lazy var scrollView: UIScrollView = UIScrollView()
    // imgView scrollView 的内部,显示图片
    lazy var imgView: UIImageView = UIImageView()
    // 菊花
    private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
}

extension PictureBroswerCell: UIScrollViewDelegate {
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imgView
    }
    //缩放完成后,移动位置
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
         //print(view?.frame)
        
        var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
        // 如果边距小于0，需要修正
        offsetX = offsetX < 0 ? 0 : offsetX
        
        var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
        offsetY = offsetY < 0 ? 0 : offsetY
        
        UIView.animateWithDuration(0.3) { () -> Void in
            scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
        }
    }
}

